package com.titaniue.java1;

import org.junit.Test;

import java.io.IOException;
import java.net.*;

/**
 * @program: JavaSenior
 * @description: UDP 网络编程
 * @author: renfei.huang
 * @create: 2021-10-26 22:39
 */
public class UDPTest {


    //发送端
    @Test
    public void sender() throws IOException {

        DatagramSocket datagramSocket = new DatagramSocket();

        String str ="我是UDP方式发送的导弹";
        byte[] data = str.getBytes();

        InetAddress localHost = InetAddress.getLocalHost();

        DatagramPacket datagramPacket = new DatagramPacket(data,0,data.length,localHost,9090);

        datagramSocket.send(datagramPacket);

        datagramSocket.close();
    }


    //接收端
    @Test
    public  void receiver() throws IOException {

        DatagramSocket datagramSocket = new DatagramSocket(9090);

        byte [] buffer = new byte[100];

        DatagramPacket datagramPacket = new DatagramPacket(buffer,0,buffer.length);

        datagramSocket.receive(datagramPacket);

        System.out.println(new String(datagramPacket.getData(),0,datagramPacket.getLength()));

        datagramSocket.close();

    }
}
